package com.gridmobi.xrtb.routers.bidding;

import com.alibaba.fastjson.JSONObject;
import com.gridmobi.xrtb.domain.dsp.DspTrackLog;
import com.gridmobi.xrtb.domain.dsp.common.AppConstant;
import com.gridmobi.xrtb.domain.dsp.common.enums.ExchangesE;
import com.gridmobi.xrtb.dspcounter.DspCounterHandler;
import com.gridmobi.xrtb.handler.InfoHandler;
import com.gridmobi.xrtb.handler.monitor.SimpleData;
import com.gridmobi.xrtb.model.rtb.MacrosTemplate;
import com.gridmobi.xrtb.util.RtbUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/")
public class ClickController {
    private static final Logger logger = LoggerFactory.getLogger(ClickController.class);
    private static final Logger clicklog = LoggerFactory.getLogger("clicklog");
    private static final Logger errorlogger = LoggerFactory.getLogger("error");
    @Autowired
    private InfoHandler infoHandler;
    @Autowired
    DspCounterHandler dspCounterHandler;


//    @Autowired
//    @Qualifier("kafkaBiddingLogger")
//    private BiddingLogger biddingLogger;
//

    @Value("${ddlurl}")
    private String ddlurl;

    @GetMapping("dspclick")
    public void click(@RequestParam Map<String, String> args, HttpServletRequest request, HttpServletResponse response) {
        String trackurl = null;
        try {
            LocalDateTime now = LocalDateTime.now();
            DspTrackLog trackArgs = RtbUtil.packTrackArgs(now, args, request);
            if (trackArgs.getCid() == null) {
                trackArgs.setCid(request.getParameter("cid"));
            }
/*            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String nextElement = headerNames.nextElement();
                String header2 = request.getHeader(nextElement);

            }*/
            /*
            构建点击ID
             */
            StringBuilder click = new StringBuilder("DSP");
            if (StringUtils.isNotBlank(trackArgs.getBidId())) {
                click.append(trackArgs.getCid() == null ? "" : trackArgs.getCid())
                        .append(AppConstant.URL_SEPARATOR)
                        .append(trackArgs.getCrid() == null ? "" : trackArgs.getCrid())
                        .append(AppConstant.URL_SEPARATOR)
                        .append(StringUtils.isBlank(trackArgs.getBidstmp()) ? System.currentTimeMillis() : trackArgs.getBidstmp());
                String clickId = click.toString();

                trackurl = SimpleData.CAMPAIGNS_LANDURL.get(trackArgs.getCid());

                trackurl = MacrosTemplate.replaceTrackurl(trackurl, trackArgs, clickId);
                trackArgs.setClickid(clickId);


            } else {

                errorlogger.warn("Click Track Bidid is null :".concat(JSONObject.toJSONString(trackArgs)));
            }
            /*记录点击*/
            dspCounterHandler.countClicks(Integer.parseInt(trackArgs.getCid()), trackArgs.getCrid(), trackArgs.getGeo(), trackArgs.getAppid(), trackArgs.getOs(), ExchangesE.getCode(trackArgs.getChannel()));


            args.put("trackurl", trackurl);

            response.sendRedirect(trackurl);

        } catch (Exception e) {
            e.printStackTrace();
            errorlogger.error("trackerror:".concat(JSONObject.toJSONString(args)), e);
        }
        clicklog.warn(JSONObject.toJSONString(args));

    }

    private String packDdlUrl(String ddlurl, DspTrackLog dspTrackLog) {
        StringBuilder stringBuilder = new StringBuilder(ddlurl);
        stringBuilder.append("?")
                .append("clickid=").append(dspTrackLog.getClickid())
                .append("&bidid=").append(dspTrackLog.getBidId())
                .append("&geo=").append(dspTrackLog.getGeo())
                .append("&cid=").append(dspTrackLog.getCid())
                .append("&devid=").append(dspTrackLog.getDevid())
                .append("&reqid=").append(dspTrackLog.getReqid())
                .append("&os=").append(dspTrackLog.getOs())
                .append("&crid=").append(dspTrackLog.getCrid())
                .append("&appbundle=").append(dspTrackLog.getAppbundle())
                .append("&domain=").append(dspTrackLog.getDomain());


        return stringBuilder.toString();
    }
}
